package com.py.credit.controller;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.*;
import com.py.credit.service.*;
import com.py.credit.utils.IpUtil;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 负责对授权模型进行操作
 *
 * @author YaoS
 * @date 2019-05-13 15:00
 */
@RestController
@RequestMapping("/authorizeModel")
public class AuthorizeModelController {

    @Autowired
    private XypjRemoteBaseService xypjRemoteBaseService;
    @Autowired
    private AuthorizeModelService modelService;
    @Autowired
    private AuthorizeRecordService recordService;
    @Autowired
    private AuthorizeLogService logService;
    @Autowired
    private ModelTestService modelTestService;
    @Autowired
    private ModelBaseService modelBaseService;

    /**
     * 功能描述:查询所有模型
     *
     * @return 申请结果
     * @author YaoS
     * @date 19/5/13 14:09
     */
    @RequestMapping(value = "/findModelList.json")
    public RestServiceResult<List> findModelList() {
        List list = modelService.findModelList();
        return new RestServiceResult<>(list);
    }

    /**
     * 功能描述:新增授权模型
     *
     * @param model 授权模型
     * @return 申请结果
     * @author YaoS
     * @date 19/5/13 14:09
     */
    @RequestMapping(value = "/addAuthorizeModel.json")
    public RestServiceResult<String> addAuthorizeModel(AuthorizeModel model, HttpServletRequest request) {
        Long userId = null;
        RestServiceResult<SysUser> userResult = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == userResult.getCode()) {
            SysUser userInfo = userResult.getData();
            if (null != userInfo) {
                userId = userInfo.getId();
            }
        } else {
            ExceptionLogger.error("AuthorizeModelController#addAuthorizeModel", "未获取到当前用户信息！");
        }
        model.setFounder(userId);
        modelService.addAuthorizeModel(model);
        return new RestServiceResult<>();
    }

    /**
     * 功能描述:分页查询申请对象信息
     *
     * @param modelName 模型名称
     * @param page      分页信息
     * @return 查询结果
     * @author YaoS
     * @date 19/5/13 14:59
     */
    @RequestMapping(value = "/findModelListForPage.json")
    public RestServiceResult<List> selectModelListForPage(
            @RequestParam(value = "modelName", defaultValue = "", required = false) String modelName,
            @RequestParam(value = "authorizeName", defaultValue = "", required = false) String authorizeName,
            Page page) {
        List<AuthorizeModel> list = modelService.selectModelListForPage(modelName, authorizeName, page);
        return new RestServiceResult<>(page.getTotalCount(), list);
    }

    /**
     * 查询已经绑定的模型
     *
     * @return 查询结果
     * @author YaoS
     * @date 19/5/13 14:59
     */
    @RequestMapping(value = "/findModelBindById.json")
    public RestServiceResult<List> findModelBind(String modelId) {
        List<AuthorizeRecord> list = modelService.findModelBind(modelId);
        return new RestServiceResult<>(list);
    }

    /**
     * 功能描述:分页查询申请对象信息
     *
     * @param authorizeId 授权id
     * @return 查询结果
     * @author YaoS
     * @date 19/5/13 14:59
     */
    @RequestMapping(value = "/findModelDetail.json")
    public RestServiceResult<AuthorizeModel> findModelDetail(String authorizeId) {
        AuthorizeModel authorizeModel = modelService.selectModelDetail(authorizeId);
        return new RestServiceResult<>(authorizeModel);
    }

    /**
     * 功能描述:更新授权模型信息
     *
     * @param model 模型
     * @return 查询结果
     * @author YaoS
     * @date 19/5/13 14:59
     */
    @RequestMapping(value = "/updateAuthorizeModel.json")
    public RestServiceResult<String> updateAuthorizeModel(AuthorizeModel model) {
        modelService.updateAuthorizeModel(model);
        return new RestServiceResult<>();
    }

    /**
     * 功能描述: 根据id删除模型
     *
     * @param id id
     * @return 删除结果
     * @author YaoS
     * @date 19/5/14 16:49
     */
    @RequestMapping(value = "/deleteAuthorizeModelById.json")
    public RestServiceResult<String> deleteAuthorizeModelById(
            @RequestParam("ids") String id) {
        RestServiceResult result = new RestServiceResult();
        int l = modelService.selectCount(id);
        if (l == 0) {
            modelService.deleteAuthorizeModelById(Integer.parseInt(id));
        } else {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("请先解除授权绑定！");
            return result;
        }
        return new RestServiceResult<>();
    }

    /**
     * 功能描述: 模型绑定
     *
     * @param modelId   模型id
     * @param recordIds 机构id
     * @return 删除结果
     * @author YaoS
     * @date 19/5/14 16:49
     */
    @RequestMapping(value = "/modelBind.json")
    public RestServiceResult<String> modelBind(
            @RequestParam("modelId") String modelId,
            @RequestParam("recordIds") String recordIds) {
        List<String> ids = null;
        if (recordIds.length() > 0) {
            ids = Arrays.asList(recordIds.split(","));
        }
        modelService.modelBind(modelId, ids);
        return new RestServiceResult<>();
    }

    /**
     * 功能描述: 授权查询
     *
     * @param token    授权查询的用户token
     * @param modelId  模型id
     * @param mainName 企业名
     * @return 删除结果
     * @author YaoS
     * @date 19/5/14 16:49
     */
    @RequestMapping(value = "/authorizeSearch.json")
    public RestServiceResult<Map> authorizeSearch(
            @RequestParam("token") String token,
            @RequestParam("modelId") String modelId,
            @RequestParam("mainName") String mainName) {
        RestServiceResult result = new RestServiceResult();
        AuthorizeModel authorizeModel = modelService.selectModel(modelId);
        if (authorizeModel == null) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("授权模型不存在！");
            return result;
        }
        AuthorizeRecord authorizeRecord = recordService.selectRecord(token);
        if (authorizeRecord == null) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("授权机构不存在或授权已超期！");
            return result;
        }
        Integer count = recordService.selectModelRecordBind(modelId,token);
        if (count != 1) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("模型未授权该机构！");
            return result;
        }
        //获取tybm
        String tybm = xypjRemoteBaseService.selectTybm(mainName);
        if ("".equals(tybm) || tybm == null) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("查询企业不存在！");
            return result;
        }
        List<String> list = new ArrayList<>(1);
        list.add(tybm);

        String batchId = UuidUtil.getUUid();
        //此处根据mainName进行跑分
        ModelTestPc modelTestPc = new ModelTestPc();
        modelTestPc.setId(batchId);
        modelTestPc.setIsDel("1");
        modelTestPc.setModelId(modelId);
        modelTestPc.setCjr(String.valueOf(authorizeRecord.getId()));
        modelTestPc.setInitIndexScore(100);
        modelTestPc.setMainType("100000");
        modelTestPc.setReportStatus("0");
        String scoreType = String.valueOf(modelBaseService.selectOne(modelId).get("scoreType"));
        modelTestService.autoScore(modelTestPc,scoreType, String.join("", list),"","","","");

        //获取ip和得分并将结果写入日志表
        Map<String, Object> map = modelTestService.getScoreDetailByPC(batchId);
        String ip = IpUtil.getInstance().getIpAddr();
        String score = String.valueOf(map.get("score"));
        AuthorizeLog log = new AuthorizeLog(score, authorizeModel.getModelName(), authorizeRecord.getDeptName(), mainName, ip);
        logService.addLog(log);
        HashMap<String, Object> resultMap = new HashMap<>(4);
        resultMap.put("mainName", mainName);
        resultMap.put("score", score);
        resultMap.put("rank", map.get("rank"));
        resultMap.put("evalInfo", map.get("evalInfo"));
        return new RestServiceResult<>(resultMap);
    }

    /**
     * 定时任务: 查询已删除的部门ID并取消关联
     *
     * @author YaoS
     * @date 19/5/27 14:27
     */
    @RequestMapping(value = "/run.json")
    public RestServiceResult run() {
        List<String> ids = xypjRemoteBaseService.selectDeleteDept();
        modelService.run(ids);
        return new RestServiceResult<>();
    }
}
